const useToString = Object.prototype.toString;

export function is(val: unknown, type: string) {
	return useToString.call(val) === `[object ${type}]`;
}

export function isString(val: unknown): val is string {
	return is(val, 'String');
}

export function isNumber(val: unknown): val is number {
	return is(val, 'Number');
}

export function isBoolean(val: unknown): val is boolean {
	return is(val, 'Boolean');
}

export function isFunction(val: unknown): val is (...args: any[]) => any {
	return typeof val === 'function';
}

export function isArray(val: unknown): val is any[] {
	return Array.isArray(val);
}

export function isObject(val: any): val is Record<any, any> {
	return val !== null && is(val, 'Object');
}

export function isDef<T = unknown>(val?: T): val is T {
	return typeof val !== 'undefined';
}

export function isUnDef<T = unknown>(val?: T): val is T {
	return !isDef(val);
}

export function isNull(val: any): val is null {
	return val === null;
}

export function isNullAndUnDef(val: unknown): val is null & undefined {
	return isUnDef(val) && isNull(val);
}

export function isNullOrUnDef(val: unknown): val is null | undefined {
	return isUnDef(val) || isNull(val);
}

export function isEmpty(val: unknown): boolean {
	if (isString(val) || isArray(val)) {
		return val.length === 0;
	}
	if (isObject(val)) {
		return Object.keys(val).length === 0;
	}
	if (val instanceof Map || val instanceof Set) {
		return val.size === 0;
	}
	return false;
}

export function isSet(val: unknown): val is Set<any> {
	return is(val, 'Set');
}

export function isMap(val: unknown): val is Map<any, any> {
	return is(val, 'Map');
}

export function isUrl(path: string): boolean {
	const reg =
		/(((^https?:(?:\/\/)?)(?:[-;:&=\+\$,\w]+@)?[A-Za-z0-9.-]+(?::\d+)?|(?:www.|[-;:&=\+\$,\w]+@)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%@.\w_]*)#?(?:[\w]*))?)$/;
	return reg.test(path);
}
